package com.jml.zlhq.app.ui;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.ui.LoginActivity.CheckBind;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.StringUtil;
import com.jml.zlhq.app.util.UIUtil;
import com.jml.zlhq.app.widgets.CommonDialog;
import com.loopj.android.http.TextHttpResponseHandler;

public class WodeFragment extends BaseFragment {
	// private TextView
	// cityChosed,userName,userTag,collectZuoping,collectDianpu,comment,setting;
	private TextView userPhone, userJinbi, danwei, jine, todayjinbi, totaljine;
	@SuppressWarnings("unused")
	private LinearLayout userTop;
	private ImageView bimg;
	public static boolean freshPage;
	private View logout, logoutLine;
	private TextView qiandao, tixian, jinbijl, how, about, tixjl, wdfx;
	private String names[] = { "消息通知", "收入记录", "返现记录", "分享记录", "提现提醒", "提现记录",
			"反馈记录", "修改密码", "关于我们", "金币宝典", "帮助中心" };
	private int image[] = { R.drawable.geren0, R.drawable.geren1,
			R.drawable.geren2, R.drawable.geren3, R.drawable.geren4,
			R.drawable.geren5, R.drawable.geren6, R.drawable.geren7,
			R.drawable.geren8, R.drawable.geren9, R.drawable.geren10, };
	private JSONObject data;
	LayoutInflater inflater1;
	Myadapter adapter;
	GridView gridView;
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				userJinbi.setText(BaseTools.getFrom("account_fees", data, "0"));
				try {
					int feescount = Integer.parseInt(BaseTools.getFrom(
							"account_fees", data, "0"));
					if (feescount > 0) {
						appContext.Login(appContext.getLoginUser()
								.put("account_fees", feescount).toString());
					}
				} catch (Exception e) {
					// TODO: handle exception
				}

				initInfo(data);
				break;
			case 2:
				boolean refreash = msg.getData().getBoolean("refreash", false);
				if (refreash)
					loadData(urlParam);
				final CommonDialog show = new CommonDialog(activity, true);
				show.show(true, true, false, "签到",
						msg.getData().getString("text"), "确定", "",
						new OnClickListener() {
							@Override
							public void onClick(View v) {
								show.dismiss();
							}
						}, null);
				break;
			default:
				break;
			}
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		inflater1 = getActivity().getLayoutInflater();
		LinearLayout leftLay = (LinearLayout) pageView
				.findViewById(R.id.content_header_left_lay);
		LinearLayout rightLay = (LinearLayout) pageView
				.findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) pageView
				.findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) pageView
				.findViewById(R.id.content_header_left_img);
		leftImage.setVisibility(View.VISIBLE);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) pageView
				.findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.VISIBLE);
		TextView centerText = (TextView) pageView
				.findViewById(R.id.content_header_center_text);
		centerText.setText("我的账户");
		TextView rightText = (TextView) pageView
				.findViewById(R.id.content_header_right_text);
		rightText.setVisibility(View.INVISIBLE);
		TextView centerChosed = (TextView) pageView
				.findViewById(R.id.content_header_center_text2);
		centerChosed.setVisibility(View.GONE);
		gridView = (GridView) pageView.findViewById(R.id.gridView);
		userTop = (LinearLayout) pageView.findViewById(R.id.main_user_top);
		bimg = (ImageView) pageView.findViewById(R.id.main_user_top_bimg);
		bimg.setLayoutParams(new FrameLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, UIUtil.winWidth * 195 / 720));
		//
		// userPhone = (TextView) pageView.findViewById(R.id.main_user_phone);
		// userJinbi = (TextView) pageView.findViewById(R.id.main_user_jinbi);
		// danwei = (TextView)
		// pageView.findViewById(R.id.main_user_jinbi_danwei);
		// jine = (TextView) pageView.findViewById(R.id.main_user_jine);
		// todayjinbi = (TextView)
		// pageView.findViewById(R.id.main_user_today_jinbi);
		// totaljine = (TextView)
		// pageView.findViewById(R.id.main_user_total_jine);
		// logout = pageView.findViewById(R.id.main_user_logout);
		// logoutLine = pageView.findViewById(R.id.main_user_logout_line);
		// qiandao = (TextView) pageView.findViewById(R.id.main_user_qiandao);
		tixian = (TextView) pageView.findViewById(R.id.main_user_tixian);
		// jinbijl = (TextView) pageView.findViewById(R.id.main_user_jinbijl);
		// tixjl = (TextView) pageView.findViewById(R.id.main_user_tixjl);
		// wdfx = (TextView) pageView.findViewById(R.id.main_user_wdfx);
		// wdfx.setOnClickListener(this);
		// userJinbi.setOnClickListener(this);
		// logout.setOnClickListener(this);
		// logoutLine.setOnClickListener(this);
		// qiandao.setOnClickListener(this);
		tixian.setOnClickListener(this);
		// jinbijl.setOnClickListener(this);
		// tixjl.setOnClickListener(this);
		// how = (TextView) pageView.findViewById(R.id.main_wo_how);
		// about = (TextView) pageView.findViewById(R.id.main_wo_about);
		// how.setOnClickListener(this);
		// about.setOnClickListener(this);
		//
		//
		freshPage = false;
		adapter = new Myadapter();
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2) {
				case 0:
					Toast.makeText(getActivity(), "开发中", 0).show();
					break;
				case 1:
					Toast.makeText(getActivity(), "开发中", 0).show();
					break;
				case 2:
					if (appContext.isLogin()) {
						Bundle data1 = new Bundle();
						data1.putString("title", "我参加的活动返现");
						data1.putInt("type", 2);
						data1.putString("url", URLs.MAIN_FANXIAN_HISTORY);
						UIUtil.openActivity(getTActivity(),
								JinbiHistoryActivity.class, data1);
					} else {
						UIUtil.openActivity(getTActivity(),
								LoginActivity.class, null, 303);
					}
					break;
				case 3:
					Toast.makeText(getActivity(), "开发中", 0).show();
					break;
				case 4:
					Toast.makeText(getActivity(), "开发中", 0).show();
					break;
				case 5:
					if (appContext.isLogin()) {
						Bundle data1 = new Bundle();
						data1.putString("title", "提现记录");
						data1.putInt("type", 3);
						data1.putString("url", URLs.MAIN_TIXIAN_HISTORY);
						UIUtil.openActivity(getTActivity(),
								JinbiHistoryActivity.class, data1);
					} else {
						UIUtil.openActivity(getTActivity(),
								LoginActivity.class, null, 304);
					}
					break;
				case 6:
					Toast.makeText(getActivity(), "开发中", 0).show();
					break;
				case 7:
					Toast.makeText(getActivity(), "开发中", 0).show();
					break;
				case 8:
					UIUtil.openActivity(getTActivity(), AboutActivity.class,
							null);
					break;
				case 9:
					Bundle data = new Bundle();
					data.putString("title", "金币宝典");
					data.putString("url",
							"http://m.51zlhq.com/html/baodian.html");
					UIUtil.openActivity(activity, CommonWebActivity.class, data);
					break;
				case 10:
					Toast.makeText(getActivity(), "开发中", 0).show();
					break;

				default:
					break;
				}
			}
		});
		// loadData(null);

		return pageView;
	}

	@Override
	public void onResume() {
		pageFresh = freshPage;
		super.onResume();
		freshPage = false;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 101) {
			if (appContext.isLogin()) {
				onClick(qiandao);
			} else {
				UIUtil.ToastMessage(activity, "未登录!");
			}
		}
		if (requestCode == 102) {
			if (appContext.isLogin()) {
				((MainActivity) activity).chooseMenu(2);
			} else {
				UIUtil.ToastMessage(activity, "未登录!");
			}
		}
		if (requestCode == 303) {
			if (appContext.isLogin()) {
				onClick(jinbijl);
			} else {
				UIUtil.ToastMessage(activity, "未登录!");
			}
		}
		if (requestCode == 304) {
			if (appContext.isLogin()) {
				onClick(tixjl);
			} else {
				UIUtil.ToastMessage(activity, "未登录!");
			}
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		if (BuildConfig.DEBUG)
			Log.i("==fr==", freshPage + "");
		if (freshPage) {
			onResume();
		}
		super.onHiddenChanged(hidden);
	}

	@Override
	public void loadData(Map<String, String> param) {
		if (appContext.isLogin()) {
			userJinbi.setPadding(0, 0, 0, 0);
			userJinbi.setBackgroundColor(getResources().getColor(
					R.color.full_transparent));
			userJinbi.setText("0");
			initInfo(null);
			logoutLine.setVisibility(View.VISIBLE);
			logout.setVisibility(View.VISIBLE);
			danwei.setVisibility(View.VISIBLE);
			if (param == null)
				param = new HashMap<String, String>();
			param.put("auth_token", appContext.getLoginUid());
			HttpService.getByText(URLs.USER_INFO, param,
					new TextHttpResponseHandler() {
						@Override
						public void onSuccess(int arg0, Header[] arg1,
								String resultStr) {
							try {
								if (BuildConfig.DEBUG)
									Log.i("==result post==", resultStr);
								JSONObject result = new JSONObject(resultStr);
								if (result.getInt("status") == 0) {
									data = result.getJSONObject("data");
								}
								mHandler.sendEmptyMessage(1);
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}

						@Override
						public void onFailure(int arg0, Header[] arg1,
								String arg2, Throwable arg3) {
							UIUtil.ToastMessage(activity, "抱歉，访问失败");
						}
					});
		} else {
			userJinbi.setText("立即登陆");
			userJinbi.setPadding(UIUtil.dip2px(activity, 8),
					UIUtil.dip2px(activity, 5), UIUtil.dip2px(activity, 5),
					UIUtil.dip2px(activity, 8));
			userJinbi.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.fillet_border_00));
			danwei.setVisibility(View.GONE);
			logoutLine.setVisibility(View.GONE);
			logout.setVisibility(View.GONE);
			initInfo(null);
			// userTag.setText("");
			// userIco.setImageResource(R.drawable.icon_touxiang110);
		}
	}

	@Override
	public void clearData() {
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.main_user_jinbi:
			if (!appContext.isLogin()) {
				UIUtil.openActivity(activity, LoginActivity.class, null);
			}
			break;
		case R.id.main_user_logout:
			appContext.Logout(WodeFragment.class.getName());
			LoginActivity.afterLogined(activity, new CheckBind() {
				@Override
				public void checkBind(String phone) {
					// TODO
				}
			});
			freshPage = false;
			loadData(null);
			break;
		case R.id.main_user_tixjl:
			if (appContext.isLogin()) {
				Bundle data1 = new Bundle();
				data1.putString("title", "提现记录");
				data1.putInt("type", 3);
				data1.putString("url", URLs.MAIN_TIXIAN_HISTORY);
				UIUtil.openActivity(this, JinbiHistoryActivity.class, data1);
			} else {
				UIUtil.openActivity(this, LoginActivity.class, null, 304);
			}
			break;
		case R.id.main_user_wdfx:
			if (appContext.isLogin()) {
				Bundle data1 = new Bundle();
				data1.putString("title", "我参加的活动返现");
				data1.putInt("type", 2);
				data1.putString("url", URLs.MAIN_FANXIAN_HISTORY);
				UIUtil.openActivity(this, JinbiHistoryActivity.class, data1);
			} else {
				UIUtil.openActivity(this, LoginActivity.class, null, 303);
			}
			break;
		case R.id.main_user_qiandao:
			if (appContext.isLogin()) {
				UIUtil.openActivity(this, qiandaoActivity.class, null);
			} else {
				UIUtil.openActivity(this, LoginActivity.class, null, 101);
			}
			break;
		case R.id.main_user_tixian:
			if (appContext.isLogin()) {
				UIUtil.openActivity(activity, TixianActivity.class, null);
				// ((MainActivity)activity).chooseMenu(2);
			} else {
				UIUtil.openActivity(this, LoginActivity.class, null, 102);
			}
			break;
		case R.id.main_user_jinbijl:
			if (appContext.isLogin()) {
				Bundle data = new Bundle();
				data.putString("title", "金币记录");
				data.putInt("type", 1);
				data.putString("url", URLs.MAIN_JINBI_HISTORY);
				UIUtil.openActivity(this, JinbiHistoryActivity.class, data);
			} else {
				UIUtil.openActivity(this, LoginActivity.class, null, 303);
			}

			break;
		case R.id.main_wo_about:
			UIUtil.openActivity(this, AboutActivity.class, null);
			break;
		case R.id.main_wo_how:
			Bundle data = new Bundle();
			data.putString("title", "金币宝典");
			data.putString("url", "http://m.51zlhq.com/html/baodian.html");
			UIUtil.openActivity(activity, CommonWebActivity.class, data);
			break;
		// case R.id.main_user_collect_zuoping:
		// Bundle data = new Bundle();
		// data.putInt("type", 1);
		// UIUtil.openActivity(this, UserColletActivity.class, data);
		// break;
		// case R.id.main_user_comment:
		// UIUtil.openActivity(activity, CommentListActivity.class, null);
		// break;
		// case R.id.main_user_setting:
		// UIUtil.openActivity(activity, SettingActivity.class, null);
		// break;
		case R.id.content_header_left_lay:
			getActivity().finish();
			break;
		default:
			break;
		}
	}

	@Override
	protected int getPageView() {
		return R.layout.main_user2;
	}

	public void initInfo(JSONObject data) {
		String name = BaseTools.getFrom("name", data, "");
		jine.setText(StringUtil.isEmpty(name) ? "" : "用户："
				+ BaseTools.getFrom("name", data, ""));
		// todayjinbi.setText(BaseTools.getFrom("today_goldcoin", data, "0"));
		// totaljine.setText(BaseTools.getFrom("total_money", data, "0"));
		// userPhone.setText(BaseTools.getFrom("name", data, "-"));
	}

	class Myadapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return names.length;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return names[arg0];
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			ViewHolder hoder = null;
			if (convertView == null) {
				convertView = inflater1.inflate(R.layout.gaid_item, null);
				hoder = new ViewHolder(convertView);
				convertView.setTag(hoder);

			} else {
				hoder = (ViewHolder) convertView.getTag();

			}
			hoder.tv.setText(names[arg0]);
			hoder.imageView.setImageResource(image[arg0]);
			return convertView;
		}

	}

	class ViewHolder {
		TextView tv;
		ImageView imageView;

		public ViewHolder(View v) {
			tv = (TextView) v.findViewById(R.id.text);
			imageView = (ImageView) v.findViewById(R.id.imag);
		}
	}
}
